package com.cedifie.lendapp.ui.loan.impl

import android.content.Context
import com.cedifie.lendapp.MyApplication
import com.cedifie.lendapp.R
import com.cedifie.lendapp.http.IHttpCallback
import com.cedifie.lendapp.mvp.presenter.MvpPresenter
import com.cedifie.lendapp.ui.loan.view.ICedLoanRepayView
import org.json.JSONArray
import org.json.JSONObject
import java.math.BigDecimal

/**
 * Cedifie
 * @Author wwdeng
 * @CreateTime: 2024/6/17 13:45
 * @Annotation：待还款 Presenter 实现
 */
class CedLoanRepayPresenterImpl(context: Context?) : MvpPresenter<ICedLoanRepayView>(context) {

    //是否展开
    private var isOpen = true
    //可申请贷款金额
    private var limitAmount = ""

    private var model: CedLoanRepayModelImpl? = null
    init {
        model = CedLoanRepayModelImpl()
    }

    /**
     * 点击展开或收起
     */
    fun onCedClickLableAction(){
        isOpen = !isOpen
        when (isOpen){
            true -> {
                mvpView?.showCedOpenViews()
            }
            else -> {
                mvpView?.showCedCloseViews()
            }
        }
    }

    /**
     * 获取贷款额度
     */
    fun loadCedLoanLimitAction(){
        model?.loadCedLoanLimitAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        //完善资料之后显示的可申请金额需要从贷款额度接口中取 amount
                        val limitArray = obj?.optJSONArray("limit")
                        if (limitArray != null && limitArray.length() > 0){
                            val limitObj = limitArray.optJSONObject(0)
                            limitAmount = limitObj.optString("amount")
                            //获取贷款信息
                            loadCedRepayInfoAction()
                        }
                    }
                    else -> {
                        mvpView?.showCedToast(data.optString("msg"))
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
            }
        })
    }

    /**
     * 获取还款信息
     */
    fun loadCedRepayInfoAction(){
        model?.loadCedRepayInfoAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        obj?.let {
                            //某些地区没有repayList，需要手动添加数据
                            if (!it.has("repayList") || it.optJSONArray("repayList") == null){
                                val unit = it.optString("currency")
                                val repayArray = JSONArray()
                                val amountItem = JSONObject()
                                amountItem.put("showName",MyApplication.app.getString(R.string.loan_repaylist_loan_amount))
                                amountItem.put("showDetail",it.optString("amount") + unit)
                                repayArray.put(amountItem)

                                val interestItem = JSONObject()
                                interestItem.put("showName",MyApplication.app.getString(R.string.loan_repaylist_interest))
                                interestItem.put("showDetail",it.optString("interest") + unit)
                                repayArray.put(interestItem)

                                val serviceFee = BigDecimal(it.optString("serviceFee","0.0")).stripTrailingZeros().toPlainString()
                                if (serviceFee.toDouble() > 0){
                                    val serviceFeeItem = JSONObject()
                                    serviceFeeItem.put("showName",MyApplication.app.getString(R.string.loan_repaylist_service_fee))
                                    serviceFeeItem.put("showDetail","$serviceFee$unit")
                                    repayArray.put(serviceFeeItem)
                                }

                                val overdueDayItem = JSONObject()
                                overdueDayItem.put("showName",MyApplication.app.getString(R.string.loan_repaylist_overdue_days))
                                overdueDayItem.put("showDetail",String.format(MyApplication.app.getString(R.string.loan_repaylist_days),it.optString("overdueDay")))
                                repayArray.put(overdueDayItem)

                                val overduePenaltyItem = JSONObject()
                                overduePenaltyItem.put("showName",MyApplication.app.getString(R.string.loan_repaylist_overdue_penalty))
                                overduePenaltyItem.put("showDetail",it.optString("overdueAmount") + unit)
                                repayArray.put(overduePenaltyItem)
                                it.put("repayList",repayArray)
                            }
                            //需要手动把总可借款额度添加到obj中
                            it.put("limitAmount",limitAmount)
                            mvpView?.showCedRepayInfo(it)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }

    /**
     * 还款
     */
    fun loadCedPayLinkAction(){
        mvpView?.showCedLoading(MyApplication.app.getString(R.string.loading))
        model?.loadCedPayLinkAction(object : IHttpCallback{
            override fun onRequestSuccess(data: JSONObject) {
                when(data.optInt("code")) {
                    0 -> {//成功
                        val obj = data.optJSONObject("obj")
                        obj?.let {
                            var repayUrl = it.optString("repayUrl","")
                            if (repayUrl.isEmpty()){
                                repayUrl = it.optString("url")
                            }
                            mvpView?.showCedPayLink(repayUrl)
                        }
                    }
                    else -> {
                        val msg = data.optString("msg")
                        mvpView?.showCedToast(msg)
                    }
                }
            }

            override fun onRequestError(error: JSONObject) {
                mvpView?.showCedToast(error.optString("errorMsg"))
            }

            override fun onRequestFinish() {
                mvpView?.hideCedLoading()
            }
        })
    }
}